package android.slc.extras.user.repository.local;

import android.slc.appbase.api.slc.callback.po.SlcEntity;
import android.slc.db_objectbox.core.DaoMaster;
import android.slc.db_objectbox.user.entity.User;
import android.slc.db_objectbox.user.service.UserDaoService;
import android.slc.extras.user.entity.UserInfo;

import java.util.List;

import io.reactivex.rxjava3.functions.Function;

/**
 * @author slc
 * @date 2020-06-19 11:21
 */
public class UserDaoServiceRepository {
    private static final UserDaoService userDaoService = DaoMaster.getService(UserDaoService.class);

    public static void saveUser(User user) {
        if (user == null || user.getId() < 1) {
            return;
        }
        User userTemp = userDaoService.get(user.getId());
        if (userTemp != null) {
            user.setId(userTemp.getId());
        }
        userDaoService.put(user);
    }

    public static void saveUserByEntity(SlcEntity<? extends User> slcEntity) {
        if (slcEntity != null && slcEntity.isSuccess()) {
            saveUser(slcEntity.getData());
        }
    }

    public static void saveUserByUserInfoEntity(SlcEntity<? extends User> slcEntity) {
        if (slcEntity != null && slcEntity.isSuccess()) {
            saveUser(slcEntity.getData());
        }
    }

    public static void saveUserList(List<? extends User> userList) {
        for (User user : userList) {
            saveUser(user);
        }
    }

    public static void saveUserInfoList(List<? extends User> userList) {
        for (User user : userList) {
            saveUser(user);
        }
    }

    public static void saveUserListByUserInfoEntity(SlcEntity<List<? extends User>> slcEntity) {
        if (slcEntity != null && slcEntity.isSuccess()) {
            saveUserInfoList(slcEntity.getData());
        }
    }

    /**
     * 保存用户
     *
     * @return
     */
    public static Function<SlcEntity<UserInfo>, SlcEntity<UserInfo>> saveUserMap() {
        return slcEntity -> {
            try {
                UserDaoServiceRepository.saveUserByEntity(slcEntity);
            } catch (Exception ignored) {

            }
            return slcEntity;
        };
    }

    /**
     * 保存用户
     *
     * @return
     */
    public static Function<SlcEntity<List<UserInfo>>, SlcEntity<List<UserInfo>>> saveUserListMap() {
        return slcEntity -> {
            try {
                if (slcEntity.isSuccess()) {
                    UserDaoServiceRepository.saveUserList(slcEntity.getData());
                }
            } catch (Exception ignored) {

            }
            return slcEntity;
        };
    }

}
